/**
 * 本质上就是问二维矩阵中连通块的数量。
 * 设置一个标记数组，循环一遍，对每个可以搜的入口深搜一遍即可
 */
#include <bits/stdc++.h>
#include <bits/extc++.h>
using namespace std;

using vi = vector<int>;

int const DR[] = {0, 0, -1, 1};
int const DC[] = {-1, 1, 0, 0};

int N, M;
vector<string> Board;
vector<vi> Flag;

void dfs(int r, int c){
    assert('1' == Board[r][c]);
    Board[r][c] = '0';

    for(int nx,ny,i=0;i<4;++i){
        nx = ((r + DR[i] + N) % N);
        ny = (c + DC[i] + M) % M;
        if('1' == Board[nx][ny]){
            dfs(nx, ny);
        }
    }
    return;
}

void work(){
    cin >> N >> M;
    Board.assign(N, {});
    for(auto & s : Board) cin >> s;
    
    // Flag.assign(N, vi(M, 0));
    int ans = 0;
    for(int i=0;i<N;++i)for(int j=0;j<M;++j){
        if('1' == Board[i][j]){
            dfs(i, j);
            ans += 1;
        }
    }
    cout << ans << "\n";
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("z.txt", "r", stdin);
#endif
    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    int nofkase = 1;
    // cin >> nofkase;

    while(nofkase--) work();
    return 0;
}